package com.zmx.user.service;

import com.zmx.common.common.exception.BusinessException;
import com.zmx.common.common.invocation.InvocationInfoProxy;
import com.zmx.common.common.service.BaseService;
import com.zmx.product.api.ProductApi;
import com.zmx.product.dto.ProductDto;
import com.zmx.user.contents.ProductContents;
import com.zmx.user.dto.MemberCartDto;
import com.zmx.user.dto.result.CartProductDTO;
import com.zmx.user.entity.MemberCart;
import com.zmx.user.repository.MemberCartRepository;
import com.zmx.user.service.mapper.MemberCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhaomxr
 */
@Service
public class MemberCartService extends BaseService<MemberCart, MemberCartDto, MemberCartRepository, MemberCartMapper> {

    @Autowired
    private ProductApi productApi;

    /**
     * 获取用户购物车
     * @param pageIndex
     * @param pageSize
     * @return
     */
    public Page getCart(Integer pageIndex, Integer pageSize) {

        Map params = new HashMap<String, Object>(1);
        params.put("memberId", InvocationInfoProxy.getUserId());
        params.put("createTime_sort", Sort.Direction.DESC);

        Page<MemberCartDto> page = this.getAll(params, pageIndex, pageSize);

        if(!page.hasContent()){
            return new PageImpl(null, page.getPageable(), page.getTotalElements());
        }

        //一次取出当前所有待展示商品，避免循环调用商品服务
        List<Long> productIds = page.getContent().stream().map(MemberCartDto::getProductId).collect(Collectors.toList());
        List<ProductDto> productDtos = productApi.findByIdIn(productIds.toArray(new Long[productIds.size()]));

        List<CartProductDTO> cartProductDTOList = new ArrayList<CartProductDTO>();
        for (MemberCartDto cart : page.getContent()) {
            List<ProductDto> productDtoList = productDtos.stream().filter(productDto -> {
                return Objects.equals(productDto.getId(), cart.getProductId());
            }).collect(Collectors.toList());
            ProductDto productDto = productDtoList.get(0);

            CartProductDTO cartProductDTO = new CartProductDTO();
            cartProductDTO.setProductId(productDto.getId());
            cartProductDTO.setProductName(productDto.getName());
            cartProductDTO.setImage(productDto.getImage());
            cartProductDTO.setQuantity(cart.getQuantity());
            cartProductDTO.setPrice(productDto.getPrice());
            cartProductDTO.setMarketPrice(productDto.getMarketPrice());
            cartProductDTO.setLimitQuantity(productDto.getLimitQuantity());
            cartProductDTO.setSeoDescription(productDto.getSeoDescription());
            cartProductDTO.setSpecification(productDto.getSpecification());
            cartProductDTO.setSize(productDto.getSize());
            cartProductDTO.setFreight(productDto.getFreight());
            cartProductDTO.setProductSn(productDto.getProductSn());
            cartProductDTO.setDefaultDisplay(productDto.getDefaultDisplay());
            cartProductDTO.setVaild(productDto.getMarketable() > 0);
            cartProductDTO.setStock((productDto.getStock() - productDto.getAllocatedStock()) >= cart.getQuantity());
            cartProductDTOList.add(cartProductDTO);
        }

        return new PageImpl(cartProductDTOList, page.getPageable(), page.getTotalElements());
    }

    /**
     * 添加购物车
     * @param productId
     * @param quantity
     */
    @Transactional(rollbackFor = Exception.class)
    public void addCart(Long productId, int quantity) {
        //判断加入购物车商品是否下架，库存是否满足添加数量
        ProductDto productDto = productApi.findById(productId);
        if (productDto.getMarketable() == 0) {
            throw new BusinessException(ProductContents.PRO_MARKETABLE_MSG);
        }
        if (productDto.getStock() - productDto.getAllocatedStock() < quantity) {
            throw new BusinessException(ProductContents.PRO_STOCK_INSUFFICIENT_MSG);
        }

        MemberCart memberCart = repository.getCartByMemberIdAndProductId(Long.valueOf(InvocationInfoProxy.getUserId()), productId);

        MemberCartDto memberCartDto = new MemberCartDto();
        //添加购物车方法改为（购物车已经存在此商品则商品数量+1）
        if (memberCart != null) {
            memberCartDto.setId(memberCart.getId());
            memberCartDto.setQuantity(memberCart.getQuantity() + 1);
            this.update(memberCartDto);
        } else {
            memberCartDto.setMemberId(Long.valueOf(InvocationInfoProxy.getUserId()));
            memberCartDto.setProductId(productId);
            memberCartDto.setQuantity(quantity);
            this.create(memberCartDto);
        }
    }

    /**
     * 删除购物车
     * @param productIds
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCart(Long[] productIds) {
        if (productIds == null || productIds.length == 0) {
            throw new BusinessException("请选择商品");
        }
        repository.deleteByMemberIdAndProductIdIn(Long.valueOf(InvocationInfoProxy.getUserId()), productIds);
    }

    /**
     * 更新购物车
     * @param productId
     * @param quantity
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCart(Long productId, int quantity) {
        //判断加入购物车商品是否下架，库存是否满足添加数量
        ProductDto productDto = productApi.findById(productId);
        if (productDto.getMarketable() == 0) {
            throw new BusinessException(ProductContents.PRO_MARKETABLE_MSG);
        }
        if (productDto.getStock() - productDto.getAllocatedStock() < quantity) {
            throw new BusinessException(ProductContents.PRO_STOCK_INSUFFICIENT_MSG);
        }

        repository.updateCart(quantity, Long.valueOf(InvocationInfoProxy.getUserId()), productId);
    }
}
